#include <opencv2/opencv.hpp>
#include <iostream>
#include <sstream>
#include <iomanip>

int main() {

    cv::VideoCapture cap("/home/xfy/cpp/tdttp/video/Infantry_blue.avi");
    double fps = cap.get(cv::CAP_PROP_FPS);

    int i = 0;
    double start_time = cv::getTickCount();
    
    cv::Mat frame;
    cv::namedWindow("Video", cv::WINDOW_NORMAL);
    
    while (1) {
        cap >> frame;
        if (frame.empty()) {
            break;
        }
        i++;
        double time = cv::getTickCount();
        double gap = time - start_time;

        if (gap >= 1.0) {
            fps = i / gap;
            i = 0;
            start_time = time;
        }
        std::stringstream fps_stream;
        fps_stream << std::fixed << std::setprecision(2) << fps;
        std::string fps_text = "FPS: " + fps_stream.str();
        
        //flag.cols宽度   flag.rows高度

        cv::putText(frame, fps_text, cv::Point(frame.cols - 150, 20),cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255, 255, 255), 2);
        cv::imshow("Video", frame);
        
        char c = (char)cv::waitKey(30);
        if (c == 27) {
            break;
        }
    }
    cap.release();
    cv::VideoCapture cap2(0);
    if (!cap2.isOpened()) {
        std::cerr << "Error: Could not open camera" << std::endl;
        return -1;
    }
    
    cv::Mat frame2;
    cv::namedWindow("Camera", cv::WINDOW_NORMAL);
    double fps2 = cap2.get(cv::CAP_PROP_FPS);
    i = 0;
    start_time = cv::getTickCount();
    
    while (1) {
        cap2 >> frame2;
        if (frame2.empty()) {
            break;
        }

        i++;
        double time = cv::getTickCount();
        double gap = (time - start_time) / cv::getTickFrequency();

        if (gap >= 1.0) {
            fps2 = i / gap;
            i = 0;
            start_time = time;
        }
        std::stringstream fps_stream;
        fps_stream << std::fixed << std::setprecision(2) << fps2;
        std::string fps_text = "FPS: " + fps_stream.str();
        
        cv::putText(frame2, fps_text, cv::Point(frame2.cols - 150, 20),cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255, 255, 255), 2);
        cv::imshow("Camera", frame2);
        
        if (cv::waitKey(1) == 27) {
            break;
        }
    }

    cap2.release();
    cv::destroyAllWindows();
    
    return 0;
}